const fs = require("fs");
const path = require("path");
const dayjs = require("dayjs");
const { exec, spawn } = require("child_process");
const { sys_parameter } = require("../middleware/baseModel");
const crypto = require("crypto");

module.exports = {
  async getParameterByKey(key) {
    let res = await sys_parameter.findOne({ where: { key: key } });
    if (res) {
      return res.value;
    }
    return "";
  },

  writeLog(msg, type) {
    let pathDir = path.join(__dirname, "../logs");
    if (!fs.existsSync(pathDir)) {
      fs.mkdirSync(pathDir);
    }

    let fileName = dayjs().format("log_YYYY.MM.DD.log");

    if (type === "error") {
      fileName = dayjs().format("logError_YYYY.MM.DD.log");
    } else if (type) {
      fileName = type + dayjs().format(`_YYYY.MM.DD.log`);
    }

    let fileFullPath = path.join(pathDir, fileName);

    if (fs.existsSync(fileFullPath)) {
      fs.appendFileSync(fileFullPath, msg);
    } else {
      fs.writeFileSync(fileFullPath, msg);
    }
  },

  execCmd(cmd) {
    let rootPath = path.join(__dirname, "../");
    cmd = `cd ${rootPath}&&${cmd}`;
    let promise = new Promise((resolve, reject) => {
      exec(cmd, (error, stdout, stderr) => {
        if (error) {
          this.writeLog(error.message, "build_error");
          console.error("error: " + error);
          reject(error);
        } else {
          this.writeLog(stdout, "build");
          resolve(stdout);
        }
      });
    });
    return promise;
  },

  delay(seconds = 1, callback) {
    let promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        if (callback) {
          callback();
        }
        resolve(true);
      }, seconds * 1000);
    });

    return promise;
  },

  getParantNode(row, moduleRows) {
    let nodeIds = [];
    if (row) {
      nodeIds.push(row.id);
    }

    let nodes = moduleRows.filter((p) => p.id === row.parent_id);
    if (nodes && nodes.length > 0) {
      let node = nodes[0];
      nodeIds.push(node.id);

      if (node.parent_id) {
        let sonNodeIds = this.getParantNode(node, moduleRows);
        if (sonNodeIds && sonNodeIds.length > 0) {
          nodeIds.push(...sonNodeIds);
        }
      }
    }

    return nodeIds;
  },
  readFileList(dir, filesList = []) {
    const files = fs.readdirSync(dir);
    files.forEach((item, index) => {
      var fullPath = path.join(dir, item);
      const stat = fs.statSync(fullPath);
      if (stat.isDirectory()) {
        this.readFileList(path.join(dir, item), filesList); //递归读取文件
      } else {
        filesList.push(fullPath);
      }
    });
    return filesList;
  },

  mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
      return true;
    } else {
      if (this.mkdirsSync(path.dirname(dirname))) {
        fs.mkdirSync(dirname);
        return true;
      }
    }
  },

  isExist(path) {
    let promise = new Promise((resolve, reject) => {
      fs.access(path, function (err) {
        if (err && err.code == "ENOENT") {
          resolve(false);
        }
        resolve(true);
      });
    });

    return promise;
  },

  getMd5: (str) => {
    let obj = crypto.createHash("md5");
    obj.update(str);
    return obj.digest("hex");
  },
};
